//
//  JsTextFiled.m
//  MpaClientIos
//
//  Created by Gikki Ares on 2023/4/8.
//  Copyright © 2023 Yach. All rights reserved.
//

/**
 1,label以非激活状态,在上面的位置时为实际值.
 2,在中间时,只是跟新了transform.
 */

#import "JsTextField.h"
#import <JsUtilitySdk/JsColorManager.h>
#import "JsBundleManager.h"
#import "JsLabel.h"
#import "JsTextFieldVm.h"
#import "JsAnimationManager.h"

@interface JsTextField()<UITextFieldDelegate>{
	
	__weak IBOutlet JsLabel *mlb_placeholder;
	__weak IBOutlet UILabel *mlb_reminder;
	__weak IBOutlet UITextField *mtf;
	IBOutlet UIView *mContentView;
	IBOutlet UIView *mRootView;
	CGAffineTransform mTransform;
	__weak IBOutlet UILabel *mLb_inactive;
	__weak IBOutlet UILabel *mLb_active;
	
	BOOL mb_isContentValid;
	uint32_t mi_updateCount;
	
	UITapGestureRecognizer * mTap;
	
}


@end

static int spacing = 3;
static UIColor * _defaultThemeColor = nil;
static float animationTime_placeholder = 0.2;
static float animationTime_separator = 0.4;
@implementation JsTextField

+ (void)load{
	_defaultThemeColor = [UIColor colorWithHex:0x4b76f9];
}

#pragma mark 01 LifeCycle
//这里self都是xib的尺寸
- (instancetype)initWithCoder:(NSCoder *)coder {
	if(self = [super initWithCoder:coder]) {
		UIView * rootView =[[[JsBundleManager jsUtilityBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil] firstObject];
		rootView.frame = self.bounds;
		[self addSubview:rootView];
		
		self.backgroundColor = [UIColor clearColor];
		rootView.backgroundColor = [UIColor clearColor];
		mtf.backgroundColor = [UIColor clearColor];
	}
	return self;
}
//代码布局.
- (instancetype)init {
	if(self = [super init]){
		UIView * rootView =[[[JsBundleManager jsUtilityBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil] firstObject];
		rootView.frame = self.bounds;
		[self addSubview:rootView];
		
		self.backgroundColor = [UIColor clearColor];
		rootView.backgroundColor = [UIColor clearColor];
		mtf.backgroundColor = [UIColor clearColor];
		[self commonInit];
	}
	return self;
}

//需要在这里更新大小.
- (void)layoutSubviews {
	mRootView.frame = self.bounds;
}

- (void)awakeFromNib {
	[super awakeFromNib];
	[self commonInit];
}

- (void)setVm:(JsTextFieldVm *)vm {
	_vm = vm;
	[self updateVmIfNeeded];
}


/**
 放到下一个runloop的原因:
 1,可能需要调用delegate方法,而delegate的设置可能在后面的地方.
 */
- (void)updateVmIfNeeded {
	if(mi_updateCount == 0) {
		dispatch_async(dispatch_get_main_queue(), ^{
//			if(mi_updateCount > 0){
				[self updateVm];
				self->mi_updateCount = 0;
//			}
		});
	}
	mi_updateCount++;
}

- (void)updateVm {
	mtf.textColor = _vm.textColor;
	mlb_placeholder.text = _vm.placeholder;
	[mtf setText:_vm.text];
	[self updateContentValid];
	if(mtf.text.length) {
		[self showPlaceHolder:NO animated:NO];
	}
	else {
		[self showPlaceHolder:YES animated:NO];
	}
	mtf.secureTextEntry = _vm.isHideContent;
	[self updateReminder];
	[self updateThemeColor:_vm.themeColor];
	mLb_inactive.backgroundColor = _vm.separatorColor_inactive;
	mlb_placeholder.font = [UIFont systemFontOfSize:self.vm.placeholderSize_inactive];
	CGAffineTransform transform = CGAffineTransformIdentity;
	float scaleY = self.vm.textSize/self.vm.placeholderSize_inactive;
	{
			//计算默认是在初始位置-inactive.
			//transform到textfiled的位置 active.
		{
				//首先平移a,再放大b,效果就是平移a之后再放大b
				//先放大b,再平移a,效果是放大b,再平移a*b.相当于把他自己的坐标系放大了,再平移.但是世界坐标新没有变.
				//平移,让label和tf的centery重叠,平移量=(placehoadler.height + tf.height)/2 + spacing;
				//y为placeholader中心到textfiled中心的距离.
			float y = (mlb_placeholder.frame.size.height + mtf.frame.size.height)/2 + spacing;
				//为了保证放大后左对齐,把锚点放在(0,0.5)
			
			transform = CGAffineTransformTranslate(transform, 0, y);
			
		}
		{
				//放大scaleY倍,让label和textfiled的字体一样大.
			transform = CGAffineTransformScale(transform, scaleY, scaleY);
		}
	}
	mTransform = transform;
	if(!_vm.text.length) {
		mlb_placeholder.transform = mTransform;
	}
	
}


- (void)commonInit {
	self.vm = [JsTextFieldVm defaultVm];
	mtf.delegate = self;
	__weak typeof(self) weakSelf = self;
	//ui界面上的改变,才会触发通知.
	[[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidChangeNotification object:mtf queue:NULL usingBlock:^(NSNotification * _Nonnull note) {
		__strong typeof(self) strongSelf = weakSelf;
		NSString * str = strongSelf->mtf.text;
		strongSelf.vm.text = str;
		[strongSelf updateContentValid];
		[strongSelf updateReminder];
	}];
	
	mTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onClickTap)];
	[self addGestureRecognizer:mTap];
	mlb_reminder.hidden = YES;
	
	mlb_placeholder.font = [UIFont systemFontOfSize:self.vm.placeholderSize_inactive];
	mtf.font = [UIFont systemFontOfSize:self.vm.textSize];
	CGAffineTransform transform = CGAffineTransformIdentity;
	float scaleY = self.vm.textSize/self.vm.placeholderSize_inactive;
	{
		//计算默认是在初始位置-inactive.
		//transform到textfiled的位置 active.
		{
				//首先平移a,再放大b,效果就是平移a之后再放大b
				//先放大b,再平移a,效果是放大b,再平移a*b.相当于把他自己的坐标系放大了,再平移.但是世界坐标新没有变.
				//平移,让label和tf的centery重叠,平移量=(placehoadler.height + tf.height)/2 + spacing;
			//y为placeholader中心到textfiled中心的距离.
			float y = (mlb_placeholder.frame.size.height + mtf.frame.size.height)/2 + spacing;
				//为了保证放大后左对齐,把锚点放在(0,0.5)
	
			transform = CGAffineTransformTranslate(transform, 0, y);
			
		}
		{
				//放大scaleY倍,让label和textfiled的字体一样大.
			transform = CGAffineTransformScale(transform, scaleY, scaleY);
		}
	}
	mTransform = transform;

	mlb_placeholder.transform = mTransform;
	mLb_active.layer.anchorPoint = CGPointMake(0.5, 0.5);
	mLb_active.transform = CGAffineTransformMakeScale(0, 1);
	mLb_active.backgroundColor = [self themeColor];
	mLb_inactive.backgroundColor = _vm.separatorColor_inactive;
	

}

- (void)updateContentValid {
	if(self.delegate && [self.delegate respondsToSelector:@selector(jsTextField:isContentValid:)]){
		mb_isContentValid = [_delegate jsTextField:self isContentValid:mtf.text];
	}
	else {
		if(mtf.text.length) {
			mb_isContentValid = true;
		}
		else {
			mb_isContentValid = false;
		}
	}
}

- (void)updateReminder {
	mlb_reminder.text = [self currentReminder];
	if(mb_isContentValid) {
		mlb_reminder.textColor = _vm.reminderColor_valid;
	}
	else {
		mlb_reminder.textColor = _vm.reminderColor_invalid;
	}
}

- (NSString *)currentReminder {
	if(mtf.text.length) {
		if(mb_isContentValid) {
			return @"数据正确";
		}
		else {
			return _vm.invalidReminder;
		}
	}
	else {
		if(!_vm.emptyReminder) {
			if(_vm.placeholder.length) {
				return [NSString stringWithFormat:@"%@不能为空",_vm.placeholder];
			}
			else {
				return @"数据不能为空";
			}
		}
		else {
			return _vm.emptyReminder;
		}
	}
}

- (void)dealloc {
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark 2 Interface
- (void)setText:(NSString *)text {
	_vm.text = text;
	mtf.text = text;
	if(text.length) {
		[self showPlaceHolder:NO animated:NO];
	}
	else {
		[self showPlaceHolder:YES animated:NO];
	}
	[self updateContentValid];
}

- (NSString *)text {
		return mtf.text;
}

- (void)shake {
	[[JsAnimationManager sharedInstance] shakeView:mlb_reminder withEth:YES];
}

- (void)setIsHideContent:(BOOL)isHideContent {
		mtf.secureTextEntry = isHideContent;
}

- (void)setThemeColor:(UIColor *)themeColor {
	[self updateThemeColor:themeColor];
}

- (void)updateThemeColor:(UIColor *)themeColor {
	_vm.themeColor = themeColor;
	mLb_active.backgroundColor = themeColor;
	if(!self.text) {
		mlb_placeholder.textColor = themeColor;
	}
}

- (UIColor *)themeColor {
	if(_vm.themeColor) {
		return _vm.themeColor;
	}
	else {
		return _defaultThemeColor;
	}
}

/**
 1,1,显示reminder,则更新reminder,并根据b2是否抖动.
 */
- (void)showReminder:(BOOL)b shake:(BOOL)b2{
	mlb_reminder.hidden = !b;
	if(b) {
		[self updateReminder];
		if(b2){
			[self shake];
		}
	}
}

- (BOOL)isContentValid {
	return mb_isContentValid;
}

#pragma mark 3 InnerFunc

- (BOOL)becomeFirstResponder {
	return [mtf becomeFirstResponder];
}

/**
 yes,将placeholder移动到中间显示,激活.
 
 */
-(void)showPlaceHolder:(BOOL)show animated:(BOOL)animated {
	if(show) {
		if(animated) {
			[UIView animateWithDuration:animationTime_placeholder animations:^{
				mlb_placeholder.transform = mTransform;
			}];
		}
		else {
			mlb_placeholder.transform = mTransform;
		}
		mlb_placeholder.textColor = _vm.placeholderColor_active;
	}
	else {
		if(animated) {
			[UIView animateWithDuration:animationTime_placeholder animations:^{
				mlb_placeholder.transform = CGAffineTransformIdentity;
			}];
		}
		else {
			mlb_placeholder.transform = CGAffineTransformIdentity;
		}
		mlb_placeholder.textColor = [self themeColor];
	}
}
-(void)showActiveSeparator:(BOOL)b {
	if(b){
		[UIView animateWithDuration:animationTime_separator delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
				self->mLb_active.transform = CGAffineTransformIdentity;
		} completion:nil];
	}
	else {
		mLb_active.transform = CGAffineTransformMakeScale(0, 1);
	}
}


- (void)setPlaceholder:(NSString *)placeholder {
	_vm.placeholder = placeholder;
	[self setVm:_vm];
}


-(UITextField *)textField {
	return mtf;
}

- (BOOL)resignFirstResponder {
	[mtf resignFirstResponder];
	bool showPlaceHolder = self.vm.text.length == 0;
	[self showPlaceHolder:showPlaceHolder animated:YES];
	return YES;
}



# pragma mark 4 Delegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
	if(_delegate && [_delegate respondsToSelector:@selector(jsTextFieldShouldReturn:)]){
		return [_delegate jsTextFieldShouldReturn:self];
	}
	else {
		//没有代理方法,默认退出FirstResponder;
		[self resignFirstResponder];
		return YES;
	}
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
	[self showPlaceHolder:NO animated:YES];
	[self showActiveSeparator:YES];
	if(_delegate && [_delegate respondsToSelector:@selector(textFieldDidBeginEditing:)]){
		[_delegate textFieldDidBeginEditing:textField];
	}
}

//结束编辑,如果没有内容,显示placeholder.
- (void)textFieldDidEndEditing:(UITextField *)textField {
	if(!mtf.text.length) {
		[self showPlaceHolder:YES animated:YES];
	}
	[self showActiveSeparator:NO];
	if(_delegate && [_delegate respondsToSelector:@selector(textFieldDidEndEditing:)]){
		[_delegate textFieldDidEndEditing:textField];
	}
}

//文字改变一次,隐藏
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
	if(_delegate && [_delegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]){
		return [_delegate textField:textField shouldChangeCharactersInRange:range replacementString:string];
	}
	return YES;
}

+ (float)advisedHeight {
	return 80;
}

#pragma mark Event
- (void)onClickTap {
	[mtf becomeFirstResponder];
}





@end
